function Mypromise(callback) {
    let self = this
    self.state ='pending'
    self.value = null
    self.reson = null
    self.successCallBack = []
    self.failCallBack = []
    function resolve(value) {
        if(self.state == 'pending') {
            self.state = 'fullied'
            self.value = value
        }
        
        setTimeout(() => {
            self.successCallBack.forEach(item => item(self.value))
        })
    }
    function reject(value) {
        if(self.state == 'pending') {
            self.state = 'rejected'
            self.reson = value
        }
        
        setTimeout(() => {
            self.failCallBack.forEach(item => item(self.reson))
        })
    }
    callback && callback(resolve, reject)
}

Mypromise.prototype.then = function(res, err) {
    res = typeof res == 'function' ? res : res => res
    err = typeof err == 'function' ? err : err => err
    let self = this
    return new Mypromise((resolve, reject) => {
        let success = () => {
            try {
                let result = res(self.value)
                result = result instanceof Mypromise ? result.then(resolve, reject) : resolve(result)
            }
            catch(err) {
                throw err
            }
        }
        let fail = () => {
            try{
                let result = err(self.reson)
                result = result instanceof Mypromise ? result.then(resolve, reject) : reject(result)
            }
            catch(err) {
                throw err
            }
        }

        if(self.state == 'pending') {
            self.successCallBack.push(res)
            self.failCallBack.push(err)
        }
        if(self.state == 'fullied') {
            success()
        }
        if(self.state == 'rejected') {
            fail()
        }
    })
}

// let promise1 = new Mypromise((resolve, reject) => {
//     resolve(new Mypromise((resolve) => {
//         resolve('hhhhh')
//     }))
// })
// promise1.then(res => console.log(res)).then(res => {
//     console.log(res)
// }).then(res => console.log(res))

let promise2 = new Promise((resolve, reject) => {

        resolve(new Promise((resolve) => {
            resolve('hhhhh')
        }))

})

promise2.then(res => {
    console.log(res);
}).then(res => {
    console.log(res)
}).then(res => console.log(res))